package org.zn.note.mybatis.core.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Java反射
 */
public class JdkReflect {

    private static final Class THIS_CLZ = JdkReflect.class;

    public void hello(String name) {
        System.out.printf("Hello %s !\n", name);
    }

    public void hello(String name, Integer age) {
        System.out.printf("Hello %s is %d !\n", name, age);
    }

    /**
     * 通过反射执行给定类的方法
     *
     * @param clz
     * @param methodName
     * @param parameters
     */
    private static void executeMethod(Class clz, String methodName, Object... parameters) {
        try {
            Class[] paraClass = new Class[parameters.length];
            for (int i = 0; i < parameters.length; i++)
                paraClass[i] = parameters[i].getClass();
            Method method = clz.getMethod(methodName, paraClass);
            method.invoke(clz.newInstance(), parameters);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        executeMethod(THIS_CLZ, "hello", "zzzz");
        executeMethod(THIS_CLZ, "hello", "zzzz", 18);
    }
}
